package com.feizhi.inventory.fragment.Inventorydetails;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.Navigation;
import androidx.viewpager2.widget.ViewPager2;

import com.aserbao.aserbaosandroid.functions.database.greenDao.db.DaoSession;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.HistoryDetailsDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDetailsDao;
import com.feizhi.inventory.MainActivity;
import com.feizhi.inventory.R;
import com.feizhi.inventory.RequestResult;
import com.feizhi.inventory.bean.InventoryDetailsBean;
import com.feizhi.inventory.database.HistoryDetails;
import com.feizhi.inventory.database.Task;
import com.feizhi.inventory.database.TaskDetails;
import com.feizhi.inventory.database.dbApp;
import com.feizhi.inventory.databinding.FragmentInventoryDetailsBinding;
import com.feizhi.inventory.fragment.Inventorydetails.alreadyinventoryfragment.AlreadyInventoryFragment;
import com.feizhi.inventory.fragment.Inventorydetails.inventorylossfragment.InventoryLossFragment;
import com.feizhi.inventory.fragment.Inventorydetails.inventoryprofitfragment.InventoryProfitFragment;
import com.feizhi.inventory.fragment.Inventorydetails.waitinventoryfragment.WaitInventoryFragment;
import com.feizhi.inventory.util.ThreadPool;
import com.google.gson.Gson;
import com.google.zxing.client.android.MNScanManager;
import com.google.zxing.client.android.model.MNScanConfig;
import com.google.zxing.client.android.other.MNScanCallback;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.lckj.lcrrgxmodule.factory.ILcUhfProduct;
import com.lckj.lcrrgxmodule.factory.LcModule;
import com.rfid.PowerUtil;
import com.rfid.trans.ReadTag;
import com.rfid.trans.TagCallback;
import com.seuic.uhf.EPC;
import com.seuic.uhf.UHFService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 盘点详情
 */
public class InventoryDetailsFragment extends Fragment implements View.OnClickListener {
    private ImageView titleBack;
    private static final String TAG = "jjh-----";
    private String jjhVoice;
    Thread thread;
    boolean ss;
    boolean flagStart;
    private ImageView titleAdd;
    private TaskDao taskDao;
    private List<Task> TaskList;
    private List<Task> taskList = new ArrayList<>();
    private DaoSession updaoSession;
    private List<Fragment> list;
    private TextView titleTextBack, titleText;
    private MainActivity mActivity;

    private HistoryDetailsDao historyDetailsDao;
    private List<HistoryDetails> historyDetails;

    private TaskDetailsDao taskDetailsDao;
    List<TaskDetails> taskDetailsList = new ArrayList<>();
    List<TaskDetails> lists, tagList, rfidList;
    private ViewPagerAdapter viewPagerAdapter;
    private FragmentInventoryDetailsBinding mBinding;
    private List<InventoryDetailsBean> data;
    private InventoryDetailsAdapter adapter;
    private String mTaskId;

    //    Intent intent;
    String taskID;
    List<EPC> epcList = new ArrayList<>();
    private Observer<Object> myObserver;
    private int mCount;
    private Gson gson = new Gson();
    private UHFService mDevice;
    private List<EPC> epcs;
    private Boolean flag = false;
    private AlertDialog dialog;
    private String myEpc;
    private String stop;
    private String aa;
    private String sss;
    private String detailsRfid;

    List<EPC> wuliEPC = new ArrayList<>();
    private String myEpc1;
    private ImageView search;
    private ImageView add;
    private PopupWindow popupWindow;
    private ArrayAdapter<String> historyAdatper;
    private int indexTT = 1;
    //    private ImageView search1;

    private String deviceModel = Build.MODEL;
    private String R501_E = "R501-E";
    private ILcUhfProduct iLcUhfProduct;
    private static SoundPool soundPool;
    private static AudioManager am;
    private static HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();

    Boolean flagStarts = true;
    MediaPlayer mediaPlayer_1;
    MediaPlayer mediaPlayer_2;



    public InventoryDetailsFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (MainActivity) getActivity();

        updaoSession = ((dbApp) mActivity.getApplication()).getDaoSession();

        Log.d("deviceModel===", deviceModel);
        if (deviceModel.equals(R501_E)) {
//            initSound();
            initRfid();
        }
        else {//8188
            // 订阅事件
            mDevice = UHFService.getInstance();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mBinding = FragmentInventoryDetailsBinding.inflate(inflater);

        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
//        initSound();
        setOnClickListener();
    }

    //处理事件
    private void setOnClickListener() {

        titleBack.setOnClickListener(this);
        titleTextBack.setOnClickListener(this);

        mBinding.search.setOnClickListener(this);

        //待盘点
        mBinding.toBeCounted.setOnClickListener(this);
        //已盘点
        mBinding.counted.setOnClickListener(this);
        //盘盈
        mBinding.inventoryProfit.setOnClickListener(this);
        //盘亏
        mBinding.inventoryLoss.setOnClickListener(this);

        mBinding.readRfid.setOnClickListener(this);

        LiveEventBus.get().with("epcrfid", String.class).observe(this, new Observer<String>() {

            @Override
            public void onChanged(String s) {
                detailsRfid = s;
            }
        });

        mBinding.viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                switch (position) {
                    case 0:
                        LiveEventBus.get().with("Task_ID").post(mTaskId);

                        break;
                    case 1:
                        LiveEventBus.get().with("Task_ID").post(mTaskId);
                        break;
                    case 2:

                        //发送接收到RFID
                        LiveEventBus.get().with("postRfid").post(detailsRfid);
                        LiveEventBus.get().with("Task_ID").post(mTaskId);
                        break;
                    case 3:
                        LiveEventBus.get().with("Task_ID").post(mTaskId);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        // 当前页面为第一页
                        mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.toBeCounted.setBackgroundResource(R.drawable.white);
                        mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
//                        LiveEventBus.get().with("Task_ID").post(mTaskId);
                        break;
                    case 1:
                        // 当前页面为第二页
                        mBinding.counted.setBackgroundResource(R.drawable.white);
                        mBinding.toBeCounted.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
//                        LiveEventBus.get().with("Task_ID").post(mTaskId);
                        break;
                    case 2:
                        // 当前页面为第三页
                        mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.toBeCounted.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryProfit.setBackgroundResource(R.drawable.white);
                        mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
                        LiveEventBus.get().with("postRfid").post(detailsRfid);
//                        LiveEventBus.get().with("Task_ID").post(mTaskId);
                        break;
                    case 3:
                        // 当前页面为第四页
                        mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.toBeCounted.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryLoss.setBackgroundResource(R.drawable.white);
//                        LiveEventBus.get().with("Task_ID").post(mTaskId);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager2.SCROLL_STATE_IDLE: // 静止状态
                        // do something
                        break;
                    case ViewPager2.SCROLL_STATE_DRAGGING: // 拖拽中
                        mBinding.viewPager2.setUserInputEnabled(false); // 禁止用户滑动切换页面
                        // do something
                        break;
                    case ViewPager2.SCROLL_STATE_SETTLING: // 自动滚动中
                        // do something
                        break;
                }
            }
        });

        mBinding.sao.setOnClickListener(this);

        mBinding.submit.setOnClickListener(this);

    }

    public static boolean start = true;
    private void initView() {

        LiveEventBus.get().with("keyCode1", int.class).observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {


                TaskList = taskDao.queryBuilder().where(TaskDao.Properties.Task_ID.eq(mTaskId), TaskDao.Properties.Task_state.eq("已盘点")).list();
                if (!TaskList.isEmpty()) {


                    return;

                }

                jjhVoice = "按钮声音关闭";
                mediaPlayer_2.stop();
                iLcUhfProduct.StopRead();

            }
        });

        LiveEventBus.get().with("keyCode", int.class).observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {

                TaskList = taskDao.queryBuilder().where(TaskDao.Properties.Task_ID.eq(mTaskId), TaskDao.Properties.Task_state.eq("已盘点")).list();
                if (!TaskList.isEmpty()) {

                    Toast.makeText(mActivity, "此表单已提交过，请勿扫码", Toast.LENGTH_SHORT).show();
                    return;

                }

                ThreadPool.runThread(() -> {
                    Log.d(TAG, "onChanged: 进来了吗");
                    if (deviceModel.equals(R501_E)) {
//                        if (start) {
                        anNiuSound();
                            mediaPlayer_2.start();
                            iLcUhfProduct.StartRead();
//                        }
//                        else {
//                            iLcUhfProduct.StopRead();
//                            mediaPlayer_1.release();
//                        }
                    }
                    else {
                        UHFService mDevices = UHFService.getInstance();
                        mDevices.setParameters(UHFService.PARAMETER_CLEAR_EPCLIST_WHEN_START_INVENTORY, 0);
                        mDevices.setPower(33);
                        mDevices.open();
                        MediaPlayer mediaPlayer = MediaPlayer.create(mActivity.getApplicationContext(), R.raw.scan);
                        start = true;
                        if (mDevices.open()) {
                            while (start){
                                if (mDevices.inventoryStart()) {
                                    int count = mDevices.getTagIDCount();
                                    if (count == 0) {

                                    } else {

                                        mediaPlayer.start();
                                        wuliEPC = mDevices.getTagIDs();
                                        Log.e("jjj", "读到了什么鬼卡: " + mDevices.getTagIDs());
                                        for (int index = 0; index < wuliEPC.size(); index++) {
                                            myEpc1 = wuliEPC.get(index).getId();
                                            try {
                                                myEpc1 = myEpc1.substring(0, 12);
                                            }catch (Exception e) {
                                                Log.e("jjj", "读到了什么鬼卡，长度不够有异常: ");
                                                e.printStackTrace();
                                            }

                                            LiveEventBus.get().with("epcrfid").post(myEpc1);
                                            LiveEventBus.get().with("Task_ID").post(mTaskId);
                                            try {
                                                Thread.sleep(1000);
                                            } catch (InterruptedException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }
                                    }
                                    mActivity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            int noCount = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("未盘点")).count();
                                            //设置带盘点数量
                                            mBinding.tvToBeCount.setText("" + noCount);

                                            int count1 = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("已盘点")).count();

                                            mBinding.yipandian.setText("" + count1);

                                            int countprofit = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("盘盈")).list().size();

                                            mBinding.textInventoryProfit.setText("" + countprofit);
                                        }
                                    });
                                }

                            }

                        } else {

                        }
                    }
                });



            }
        });

        LiveEventBus.get().with("epcrfid", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

                aa = s;

            }
        });

        initScanConfig();

        DaoSession daoSession = ((dbApp) mActivity.getApplication()).getDaoSession();
        taskDetailsDao = daoSession.getTaskDetailsDao();
        taskDao = daoSession.getTaskDao();
        historyDetailsDao = daoSession.getHistoryDetailsDao();

        List<HistoryDetails> historyDetails1 = new ArrayList<>();
        historyDetails = historyDetailsDao.loadAll();

        Bundle bundle = getArguments();
        if (bundle != null) {
            mTaskId = bundle.getString("taskID");
            mCount = bundle.getInt("count");

        }

        LiveEventBus.get().with("idid").post(mTaskId);

        LiveEventBus.get().with("Task_ID").post(mTaskId);

        long idCount = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId)).count();

        //接收上个页面传过来的单号
        mBinding.inventoryNumber.setText(mTaskId);

        int noCount = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("未盘点")).count();
        int yiCount = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("已盘点")).count();
        int profitCount = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("盘亏")).list().size();

        //接收上个页面传过来的盘点总数
        mBinding.inventoryCount.setText("" + (noCount + yiCount + profitCount));

        titleAdd = mActivity.findViewById(R.id.title_add);


        titleText = mActivity.findViewById(R.id.title_text);
        titleTextBack = mActivity.findViewById(R.id.title_text_back);
        titleBack = mActivity.findViewById(R.id.title_back);

        titleTextBack.setVisibility(View.VISIBLE);
        titleBack.setVisibility(View.VISIBLE);
        titleText.setText("盘点详情");
        titleAdd.setVisibility(View.GONE);

        //添加Fragment页面，设置ViewPager2的适配器
        list = new ArrayList<>();
        list.add(new WaitInventoryFragment());
        list.add(new AlreadyInventoryFragment());
        list.add(new InventoryProfitFragment());
        list.add(new InventoryLossFragment());
        viewPagerAdapter = new ViewPagerAdapter(mActivity.getSupportFragmentManager(), getLifecycle(), list);
        mBinding.viewPager2.setAdapter(viewPagerAdapter);

    }

    /**
     * 初始化扫码
     */
    private MNScanConfig scanConfig;

    private void initScanConfig() {
        if (scanConfig == null) {
            scanConfig = new MNScanConfig.Builder()
                    //设置完成震动
                    .isShowVibrate(true)
                    //扫描完成声音
                    .isShowBeep(true)
                    //显示相册功能
                    .isShowPhotoAlbum(false)
                    //显示闪光灯
                    .isShowLightController(false)
                    //自定义文案--不展示
                    .setScanHintText("识别二维码")
                    //自定义文案颜色
                    .setScanHintTextColor("#FFFFFF")
                    //自定义文案大小（单位sp）
                    .setScanHintTextSize(15)
                    //是否显示缩放控制器
                    .isShowZoomController(false)
                    //显示缩放控制器位置 .setZoomControllerLocation(MNScanConfig.ZoomControllerLocation.Bottom)
                    //背景颜色
                    // .setBgColor("#33FF0000")
                    //扫描线样式
                    .setLaserStyle(MNScanConfig.LaserStyle.Line)
                    //扫描线的颜色
                    .setScanColor("#00FF33")
                    //网格扫描线的列数
                    //  .setGridScanLineColumn(30)
                    //高度偏移值（单位px）+向上偏移，-向下偏移
                    .setScanFrameHeightOffsets(-50)
                    //是否全屏范围扫描
                    .setFullScreenScan(false)
                    //二维码标记点
                    .isShowResultPoint(true)
                    // 设置标记点的大小、色值
                    .setResultPointConfigs(36, 20, 2, "#00FF33", "#00FF33")//E61F55 FFFFFFFF
                    //状态栏设置：颜色，是否黑色字体
                    .setStatusBarConfigs("#00000000", true)
                    //是否支持多二维码同时扫出,默认false,多二维码状态不支持条形码
                    .setSupportMultiQRCode(true)

                    .setSupportZoom(true)
                    //网格高度
                    .setGridScanLineHeight(300)
                    .builder();
        }
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search:
                // 用于PopupWindow的View
                View contentView = LayoutInflater.from(mActivity).inflate(R.layout.popup_layout, null, false);
                // 创建PopupWindow对象，其中：
                // 第一个参数是用于PopupWindow中的View，第二个参数是PopupWindow的宽度，
                // 第三个参数是PopupWindow的高度，第四个参数指定PopupWindow能否获得焦点  ,其中有好几个构造,我只是用了其中一个
                PopupWindow window = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
                // 设置PopupWindow的背景   必须设置背景,要不setoutsidetouchable(true)不管用,按back键也不会管用,具体看源码,如果背景不为空的话,会在外面套一层布局
//                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                // 设置PopupWindow是否能响应外部点击事件
                window.setOutsideTouchable(true);
                // 设置PopupWindow是否能响应点击事件,具体是其中的item的响应事件
                window.setTouchable(true);
                // 显示PopupWindow，其中：
                // 第一个参数是PopupWindow的锚点，第二和第三个参数分别是PopupWindow相对锚点的x、y偏移
                window.showAtLocation(mActivity.getWindow().getDecorView(), Gravity.CENTER, 0, 0);


                @SuppressLint({"MissingInflatedId", "LocalSuppress"})
                Button mBtnSearch = contentView.findViewById(R.id.search_ok);
                Button mBtnNo = contentView.findViewById(R.id.search_no);
                AutoCompleteTextView screen_content = contentView.findViewById(R.id.screen_content);
                AutoCompleteTextView autoCompleteTextView = contentView.findViewById(R.id.screen_state);
                List<String> name  = new ArrayList<>();
                for (int i = 0; i < historyDetails.size(); i++) {

                    name.add(historyDetails.get(i).getName());

                }
                historyAdatper = new ArrayAdapter<>(mActivity, android.R.layout.simple_dropdown_item_1line, name);
                String[] data = {"已盘点", "待盘点", "盘盈", "盘亏"};
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(mActivity, android.R.layout.simple_dropdown_item_1line, data) {
                    @NonNull
                    @Override
                    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                        TextView textView = (TextView) super.getView(position, convertView, parent);
                        textView.setGravity(Gravity.CENTER); // 设置文本居中显示
                        return textView;
                    }

                    @Override
                    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                        TextView textView = (TextView) super.getDropDownView(position, convertView, parent);
                        textView.setGravity(Gravity.CENTER); // 设置文本居中显示

                        // 设置背景色
//                        int backgroundColor = getResources().getColor(R.color.dropdown_background_color);
                        textView.setBackgroundColor(R.color.dropdown_background_color);

                        int padding = getContext().getResources().getDimensionPixelSize(R.dimen.dropdown_item_padding);
                        textView.setPadding(padding,padding,padding,padding);
                        return textView;
                    }
                };
                autoCompleteTextView.setAdapter(adapter);
                autoCompleteTextView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        autoCompleteTextView.showDropDown();
                    }
                });
                screen_content.setAdapter(historyAdatper);
                screen_content.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        screen_content.showDropDown();

                        screen_content.requestFocusFromTouch();

                        screen_content.requestFocus();

                        InputMethodManager inputMethodManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputMethodManager.showSoftInput(screen_content, InputMethodManager.SHOW_IMPLICIT);
                    }
                });

                mBtnNo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });
                mBtnSearch.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String search_conditions = screen_content.getText().toString();
                        String screen_state = autoCompleteTextView.getText().toString();
                        if (TextUtils.isEmpty(screen_state)) {
                            Toast.makeText(mActivity, "请选择筛选条件", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        switch (screen_state) {
                            case "待盘点":
                                LiveEventBus.get().with("search_condition2").post(search_conditions);
                                mBinding.viewPager2.setCurrentItem(0, false);
                                break;
                            case "已盘点":
                                LiveEventBus.get().with("search_condition1").post(search_conditions);
                                mBinding.viewPager2.setCurrentItem(1, false);

                                break;
                            case "盘盈":
                                LiveEventBus.get().with("search_condition3").post(search_conditions);
                                mBinding.viewPager2.setCurrentItem(2, false);

                                break;
                            case "盘亏":
                                LiveEventBus.get().with("search_condition4").post(search_conditions);
                                mBinding.viewPager2.setCurrentItem(3, false);

                                break;
                            default:break;

                        }


                        window.dismiss();


                    }
                });
                break;

            case R.id.title_back:
            case R.id.title_text_back:
                backFragment();
                break;

            case R.id.read_rfid://读取RIFD
                TaskList = taskDao.queryBuilder().where(TaskDao.Properties.Task_ID.eq(mTaskId), TaskDao.Properties.Task_state.eq("已盘点")).list();
                if (!TaskList.isEmpty()) {

                    Toast.makeText(mActivity, "此表单已提交过，请勿再次识别RFID", Toast.LENGTH_SHORT).show();
                    return;

                }

                if (mBinding.textReadRfid.getText().equals("取消读卡")) {
                    mBinding.textReadRfid.setText("RFID读取");
                    flagStarts = false;
//                    if (deviceModel.equals(R501_E)) {
//                        iLcUhfProduct.StopRead();
//                        mediaPlayer_1.release();
//                    }
                    readRFID();
                    Log.d("flagStarts====", String.valueOf(flagStarts));
                }else {
                    myAlertDialog();
                }
                break;

            case R.id.to_be_counted://待盘点
                indexTT = 1;
                mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.toBeCounted.setBackgroundResource(R.drawable.white);
                mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.viewPager2.setCurrentItem(0, false);
//                LiveEventBus.get().with("Task_ID").post(mTaskId);
                break;

            case R.id.counted://已盘点
                indexTT = 2;
                mBinding.counted.setBackgroundResource(R.drawable.white);
                mBinding.toBeCounted.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.viewPager2.setCurrentItem(1, false);
//                LiveEventBus.get().with("Task_ID").post(mTaskId);
                break;

            case R.id.inventory_profit://盘盈
                indexTT = 3;
                mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.toBeCounted.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryProfit.setBackgroundResource(R.drawable.white);
                mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.viewPager2.setCurrentItem(2, false);
//                LiveEventBus.get().with("postRfid").post(detailsRfid);
//                LiveEventBus.get().with("Task_ID").post(mTaskId);
                break;

            case R.id.inventory_loss://盘亏
                indexTT = 4;
                mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.toBeCounted.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryLoss.setBackgroundResource(R.drawable.white);
                mBinding.viewPager2.setCurrentItem(3, false);
//                LiveEventBus.get().with("Task_ID").post(mTaskId);
                break;

            case R.id.sao://扫码按钮
                TaskList = taskDao.queryBuilder().where(TaskDao.Properties.Task_ID.eq(mTaskId), TaskDao.Properties.Task_state.eq("已盘点")).list();
                if (!TaskList.isEmpty()) {

                    Toast.makeText(mActivity, "此表单已提交过，请勿再次扫码", Toast.LENGTH_SHORT).show();
                    return;

                }
                startScan(k -> {

                    LiveEventBus.get().with("scan_code").post(k);

                });

                break;

            case R.id.submit:
                TaskList = taskDao.queryBuilder().where(TaskDao.Properties.Task_ID.eq(mTaskId), TaskDao.Properties.Task_state.eq("已盘点")).list();
                if (!TaskList.isEmpty()) {
                    Toast.makeText(mActivity, "此表单已提交过，请勿重复提交", Toast.LENGTH_SHORT).show();
                    return;
                }


                taskList.addAll(TaskList);

                AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
                        .setTitle("确定是否提交?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Toast.makeText(mActivity, "提交成功", Toast.LENGTH_SHORT).show();

                                String taskSql = "update " + updaoSession.getTaskDao().getTablename() + " set " + TaskDao.Properties.Task_state.columnName + "='已盘点' where "
                                        + TaskDao.Properties.Task_ID.columnName + "='" + mTaskId + "'";
                                updaoSession.getDatabase().execSQL(taskSql);

                                String sql = "update " + updaoSession.getTaskDetailsDao().getTablename() + " set " +
                                        TaskDetailsDao.Properties.State.columnName + "='盘亏' where " +
                                        TaskDetailsDao.Properties.State.columnName + "='" + "未盘点" + "'" +
                                        "and " + TaskDetailsDao.Properties.TaskID.columnName + "='" + mTaskId + "'";
                                updaoSession.getDatabase().execSQL(sql);
                                Navigation.findNavController(mActivity, R.id.fragment_my).navigateUp();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).create();
                alertDialog.show();
                break;

            default:
                break;
        }
    }

    //弹出对话框
    private void myAlertDialog() {
        dialog = new AlertDialog.Builder(mActivity)
                .setTitle("开始RFID识别......\n")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {


                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        mBinding.textReadRfid.setText("取消读卡");
                        flagStarts = true;
                        Log.d("flagStarts====myAlertDialog", String.valueOf(flagStarts));
                        readRFID();
                    }
                })
                .create();
        dialog.show();
    }

    /**
     * 读取RIFD的方法
     */
    private void readRFID() {
        dialog.dismiss();

        DaoSession rfiddaoSession = ((dbApp) mActivity.getApplication()).getDaoSession();
        taskDetailsDao = rfiddaoSession.getTaskDetailsDao();

        Log.d("flagStarts====readRFID", String.valueOf(flagStarts));

        Log.d("deviceModel", deviceModel);

        if (deviceModel.equals(R501_E)) {
            initSound();
            if (mBinding.textReadRfid.getText().equals("取消读卡")) {

                iLcUhfProduct.StartRead();



//                ThreadPool.runThread(() -> {
//                    while (flagStarts) {
//                        int len1 = taskDao.queryBuilder().where(TaskDao.Properties.Task_ID.eq(mTaskId), TaskDao.Properties.Task_state.eq("已盘点")).list().size();
//                        if (len1 != 0) {
////                            iLcUhfProduct.StopRead();
////                            flagStarts = false;
//                            break;
//                        }
//                    }
//                });
            } else if (mBinding.textReadRfid.getText().equals("RFID读取")) {
                Log.d("flagStarts====readRFID000", String.valueOf(flagStarts));
                iLcUhfProduct.StopRead();
                mediaPlayer_1.release();
            }
        } else {
            //创建一个UHF对象
            mDevice.setParameters(UHFService.PARAMETER_CLEAR_EPCLIST_WHEN_START_INVENTORY, 0);
            mDevice.setPower(33);

            flagStarts = true;
            mDevice.open();
            if (mDevice.open()) {

                read1();

            } else {
                Toast.makeText(mActivity, "UFH打开失败", Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void read1() {
        MediaPlayer mediaPlayer = MediaPlayer.create(mActivity.getApplicationContext(), R.raw.scan);
        ThreadPool.runThread(() -> {
            if (mDevice.inventoryStart()) {

                while (flagStarts) {

                    int tagIDCount = mDevice.getTagIDCount();//读到卡的数量
                    if (tagIDCount == 0) {

                    } else {
                        mediaPlayer.start();
                        epcList = mDevice.getTagIDs();
                        for (int index = 0; index < epcList.size(); index++) {
                            myEpc = epcList.get(index).getId();
                            try {

                                myEpc = myEpc.substring(0, 12);

                            }catch (Exception e) {
                                e.printStackTrace();
                            }

                            LiveEventBus.get().with("epcrfid").post(myEpc);
                            LiveEventBus.get().with("Task_ID").post(mTaskId);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }


                        }
                        // 在主线程中动态更新 UI 的操作
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                int noCount = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("未盘点")).count();
                                //设置带盘点数量
                                mBinding.tvToBeCount.setText("" + noCount);

                                int count = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("已盘点")).count();

                                mBinding.yipandian.setText("" + count);

                                int countprofit = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("盘盈")).list().size();

                                mBinding.textInventoryProfit.setText("" + countprofit);
//

                            }
                        });

                        int len1 = taskDao.queryBuilder().where(TaskDao.Properties.Task_ID.eq(mTaskId), TaskDao.Properties.Task_state.eq("已盘点")).list().size();
                        if (len1 != 0) {
                            mDevice.inventoryStop();
                            break;
                        }

                    }


                }
            } else {

                Toast.makeText(mActivity, "打开连续读卡失败", Toast.LENGTH_SHORT).show();

            }
            mediaPlayer.release();

        });


//        }
    }

    public void startScan(RequestResult<String> requestResult) {
// 开启扫描
        MNScanManager.startScan(mActivity, scanConfig, new MNScanCallback() {
            public void onActivityResult(int resultCode, Intent data) {
                switch (resultCode) {
                    case MNScanManager.RESULT_SUCCESS:
                        requestResult.request(data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS));
                        String datas = gson.toJson(data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS));
                        String result = datas.replaceAll("\"", "");

                        break;
                    case MNScanManager.RESULT_FAIL:
                        // 错误提示：比如：初始化相机失败等
                        String resultError = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR);
                        break;
                    case MNScanManager.RESULT_CANCLE:
                        //    ZZSSLog.e("取消扫码");
                        break;
                }
            }
        });
    }

    //返回上一层fragment
    private void backFragment() {
        Navigation.findNavController(mActivity, R.id.fragment_my).navigateUp();
    }

    private void initSound() {
        mediaPlayer_1 = MediaPlayer.create(mActivity.getApplicationContext(), R.raw.barcodebeep);
    }
    private void anNiuSound() {
        mediaPlayer_2 = MediaPlayer.create(mActivity.getApplicationContext(), R.raw.barcodebeep);
    }

    private void initRfid() {
        PowerUtil.power("1");
        iLcUhfProduct = new LcModule(getContext()).createProduct();
        iLcUhfProduct.Connect();
        MsgCallback callback = new MsgCallback();
        iLcUhfProduct.SetCallBack(callback);//读取标签的回调
    }

    public class MsgCallback implements TagCallback {

        @Override
        public void tagCallback(ReadTag readTag) {
            if (readTag != null) {
//                initSound();


                if (mediaPlayer_1 != null) {
                    mediaPlayer_1.start();
                }
                String epc = readTag.epcId.toUpperCase();
                if (!epcList.contains(epc)) {
                    Log.d("epc-------", epc);
                    //处理获取到的epc
                    try {
                        epc = epc.substring(0, 12);
                    }catch (Exception e) {
                        Log.e("jjj", "读到了什么鬼卡，长度不够有异常: ");
                        e.printStackTrace();
                    }

//                    LiveEventBus.get().with("epcrfid").post(myEpc);
//                    LiveEventBus.get().with("Task_ID").post(mTaskId);

                    LiveEventBus.get().with("epcrfid").post(epc);
                    LiveEventBus.get().with("Task_ID").post(mTaskId);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            int noCount = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("未盘点")).count();
                            //设置带盘点数量
                            mBinding.tvToBeCount.setText("" + noCount);

                            int count1 = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("已盘点")).count();

                            mBinding.yipandian.setText("" + count1);

                            int countprofit = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("盘盈")).list().size();

                            mBinding.textInventoryProfit.setText("" + countprofit);
                        }
                    });

                }
            }
        }

        @Override
        public int tagCallbackFailed(int i) {
            return 0;
        }

        @Override
        public int CRCErrorCallBack(int i) {
            return 0;
        }

        @Override
        public void FinishCallBack() {

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        int noCount = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("未盘点")).count();
        //设置带盘点数量
        mBinding.tvToBeCount.setText("" + noCount);

        int count = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("已盘点")).count();

        mBinding.yipandian.setText("" + count);

        int countLoss = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("盘亏")).count();
        mBinding.textLoss.setText("" + countLoss);

        int countprofit = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(mTaskId), TaskDetailsDao.Properties.State.eq("盘盈")).list().size();

        mBinding.textInventoryProfit.setText("" + countprofit);
    }

    @Override
    public void onDestroy() {
        flagStarts = false;
        PowerUtil.power("0");
        iLcUhfProduct.DisConnect();
        if (mediaPlayer_1 != null) {
            mediaPlayer_1.release();
        }
        super.onDestroy();
    }

//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        Log.e("TAG", "onKeyDown: " + keyCode);
//        if (deviceModel.equals(R501_E)) {
//            if (keyCode == 305 || keyCode == 619 || keyCode == 621) {//修改键值,S70手柄的键值:619,N41U上的手柄按键的键值:621
//                TaskList = taskDao.queryBuilder().where(TaskDao.Properties.Task_ID.eq(mTaskId), TaskDao.Properties.Task_state.eq("已盘点")).list();
//                if (!TaskList.isEmpty()) {
//
//                    Toast.makeText(mActivity, "此表单已提交过，请勿再次识别RFID", Toast.LENGTH_SHORT).show();
//
//                }
//                else {
//                    if (mBinding.textReadRfid.getText().equals("取消读卡")) {
//                        mBinding.textReadRfid.setText("RFID读取");
//                        flagStarts = false;
//                        if (deviceModel.equals(R501_E)) {
//                            iLcUhfProduct.StopRead();
//                            mediaPlayer_1.release();
//
//
//                        }
//                        Log.d("flagStarts====", String.valueOf(flagStarts));
//                    }else {
//                        mBinding.textReadRfid.setText("取消读卡");
//                        flagStarts = true;
//                        Log.d("flagStarts====myAlertDialog", String.valueOf(flagStarts));
//                        readRFID();
//                    }
//                }
//
//
//            }
//        }
//        return true;
//    }
}